1. Functions in JavaScript
A function in JavaScript is a block of code that can be executed multiple times from different parts of your code. It is a reusable block of code that can be called multiple times from different parts of your code. Functions are used to perform a specific task and can be reused throughout your code.
Syntax
function nameOfFunction(parameters) {
// code to be executed
}
Example
function greet(name) {
console.log("Hello, " + name);
}
greet("John");
Explanation:
In the above example, we have a function named `greet` that takes a parameter `name`. When we call the function with the argument `"John"`, it prints "Hello, John" to the console.
2. Function with Parameter
A function with a parameter is a function that takes one or more arguments when it is called. The arguments are passed to the function when it is called, and the function can use these arguments to perform its task.
Explanation
function greetUser(name) {
console.log("Hello, " + name + "!");
}
greetUser("Alice"); // Output: Hello, Alice!
greetUser("Bob"); // Output: Hello, Bob!
Explanation:
name is the parameter of the function.
You can pass different arguments when calling the function.
3. Function with Return Value
A function with a return value is a function that returns a value when it is called. The return value can be a number, a string, an object, or any other type of data. The return value is used by the caller of the function to perform its task.
Explanation
function add(a, b) {
return a + b; // Returns the sum of a and b
}
let result = add(5, 7);
console.log("Result:", result); // Output: Result: 12
The function returns the result of a + b to the caller.
Why Use Functions?
Reusability: Write code once, use it multiple times.
Modularity: Break large programs into smaller, manageable parts.
Maintainability: Easier to update and debug code.
Code Readability: Functions improve code structure.